Step 30: Vitest UI & Coverage

so we updated all our tests to use the test database. Let’s run all the tests:

yarn test

Notice some tests fail! Try to run each test file separately, and observe all the tests in each file pass! This is strange — why some tests fail when we run all tests files?

The issue resides in how Vitest works! To speed up the testing process, Vitest by default runs the tests in parallel in multiple threads. Since we use a shared test database, we need to ensure the tests are run sequentially in a single thread (rather than creating a worker pool of child processes that run tests). The good news is that Vitest provides an option to disable this feature. Update the package.json as follows:

"test": "vitest --no-threads --no-isolate",

Run the tests again and see all tests in all files pass! The flags we passed to Vitest ensured the tests run sequentially.

Speaking of Vitest, let’s explore a few other features! Add the following dev dependency:

yarn add -D @vitest/coverage-c8

Update the package.json and add the coverage command:

"coverage": "vitest run --coverage --no-threads --no-isolate",

Then run the coverage test!

yarn coverage

Notice you get a report in the terminal. Moreover, there is a coverage folder! (Make sure to exclude it from git). Feel free to open the coverage/index.html in the browser and explore it.

Let’s explore one other tool built into Vitest! Add the following dev dependency:

yarn add -D @vitest/ui

Update the package.json by adding the following to command:

"test:ui": "vitest --ui --no-threads --no-isolate"

Then run the following command and see the Vitest UI!

yarn test:ui

Explore the UI. It is a unique tool built for Vitest.